<template>
  <div class="myUpdateHeader">
    <myheader title="修改头像" @updataInfo="setHeadImg" rightBtn="确定修改"></myheader>

    <!-- 存放内容 -->
    <div class="updateHeadimg">
      <li class="li_img">
        <img class="headImg" :src="headimg" alt @click="showImg" />
        <div class="li_div">
          <van-uploader :after-read="afterRead" accept="image/*">
            <van-button icon="plus" @click="setHeadImg" type="primary">
              <van-icon name="photograph" size="40px" />
            </van-button>
          </van-uploader>
        </div>
      </li>
    </div>
    <button class="mybut" @click="setHeadImg">确定上传</button>
  </div>
</template>

<script>
import myheader from '../../comon/myheader.vue' //头文件
import { ImagePreview, Notify } from 'vant'
export default {
  components: {
    myheader,
  },
  data() {
    return {
      UrlHeadImg: '/api/user/img?img=',
      headimg: '',
      user: {},
      file: '',
    }
  },
  created() {
    this.user = this.$store.getters.getUserInfo
    this.headimg = this.user.avatar
  },
  methods: {
    //查看到图片
    showImg() {
      ImagePreview({
        images: [this.headimg],
        closeable: true,
      })
    },
    //图片读取后的回调函数
    afterRead(file) {
      this.file = file
      this.headimg = file.content
    },
    /**
     * 取消修改
     */
    approve() {
      // console.log(this.$store)
      this.$store.commit('setUser', this.thisUser)
      // this.$store.setUser(this.thisUser),
      this.$store.commit('RELEASE').then(() => {
        console.log('开始返回了')
        this.$router.go(-1)
      })
    },
    setHeadImg() {
      //file为 你读取成功的回调文件信息
      //new 一个FormData格式的参数
      let file = new FormData()
      file.append('file', this.file.file)
      let config = {
        headers: {
          //添加请求头
          'Content-Type': 'multipart/form-data',
        },
      }
      return new Promise((resolve, reject) => {
        this.$axios
          .post('/sys/user/modifyAvatar/' + this.user.id, file, config)
          .then((res) => {
            if (res.data.code == 200) {
              // 更新vuex中的最新用户信息
              this.$store.commit('SET_USER', res.data.data)
              Notify({ type: 'success', message: '修改头像成功' })
              this.$router.push('/home/my')
            }
          })
      })
    },
  },
}
</script>

<style scoped>
.myUpdateHeader {
  overflow: hidden;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  margin-top: 46px;
}

.updateHeadimg {
  margin-top: 30px;
}
.li_img {
  width: 100%;
  position: relative;
}
.li_div {
  position: absolute;
  bottom: -20%;
  right: 17%;
  transform: translate(-50%, -50%);
}
.headImg {
  display: block;
  width: 150px;
  height: 150px;
  margin: auto;
  border-radius: 50%;
}

.mybut {
  height: 1.25rem;
  width: 50%;
  text-align: center;
  line-height: 1.25rem;
  background-color: #39a9ed;
  margin: 1.25rem auto;
  font-size: 16px;
}
</style>
